package mysql

import (
	"cloud-storage/global"
	"cloud-storage/lib"
	"cloud-storage/utils"
)

type User struct {
	Id          int
	OpenId      string
	FileStoreId int
	UserName    string
	Phone       string
	Password    string
	ImagePath   string
}

// UserParam 注册
type UserParam struct {
	Phone    string `json:"phone" form:"phone"`
	Code     string `json:"code" form:"code"`
	UserName string `json:"user_name" form:"user_name"`
	Password string `json:"password" form:"password"`
}

// CreateUser 创建用户
func CreateUser(p *UserParam) error {
	user := &User{
		Phone:       p.Phone,
		UserName:    lib.AppSetting.UserName + utils.RandNumber(),
		FileStoreId: 0,
	}
	err := global.DB.Create(user).Error
	fileStore := FileStore{
		UserId:      user.Id,
		CurrentSize: 0,
		MaxSize:     12345678,
	}
	err = global.DB.Create(&fileStore).Error
	user.FileStoreId = fileStore.Id
	err = global.DB.Save(&user).Error
	return err
}

// GetPhone 查询用户手机号是否存在
func GetPhone(p *UserParam) (num int64, err error) {
	var user User
	result := global.DB.Where("phone = ?", p.Phone).First(&user)
	return result.RowsAffected, result.Error
}

// GetPassword 查询用户密码
func GetPassword(p *UserParam) (password string, err error) {
	err = global.DB.Model(&User{}).Select("password").Where("phone = ?", p.Phone).First(&password).Error
	return
}

// UpdatePassword 更新密码
func UpdatePassword(p *UserParam) error {
	err := global.DB.Model(&User{}).Where("phone", p.Phone).Update("password", p.Password).Error
	return err
}

// UpdateName 更改用户名
func UpdateName(name, phone string) error {
	err := global.DB.Model(&User{}).Where("phone = ?", phone).Update("user_name", name).Error
	return err
}

//UpdateImage 更改头像
func UpdateImage(imagePath, phone string) error {
	err := global.DB.Model(&User{}).Where("phone = ?", phone).Update("image_path", imagePath).Error
	return err
}

//GetImage 获取头像
func GetImage(phone string) (imagePath string, err error) {
	err = global.DB.Model(&User{}).Select("image_path").Where("phone = ?", phone).First(&imagePath).Error
	return
}

// GetUserInfo 根据手机号查询用户
func GetUserInfo(phone interface{}) (user User, err error) {
	err = global.DB.Find(&user, "phone = ?", phone).Error
	return
}
